<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="产品名称" prop="productIdentification">
        <el-select v-model="queryParams.productIdentification" placeholder="请选择产品标识" @change="dictValue">
          <el-option v-for="dict in dict.type.product_verification_identification" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="产品条码" prop="productSn">
        <el-input style="width: 300px;" type="text" maxlength="100" v-model="queryParams.productSn"
          placeholder="请输入产品条码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="生产时间" prop="productionTime">
        <el-date-picker v-model="dateRange" style="width: 280px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" @change="dataCheng"
          :clearable="false"></el-date-picker>
      </el-form-item>

      <el-form-item label="是否返工" prop="isRework">
        <el-select v-model="queryParams.isRework" placeholder="请选择是否返工" clearable>
          <el-option v-for="dict in dict.type.yes_or_no" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.product_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
        v-hasPermi="['mes:productionRecord:remove']">删除
      </el-button> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="downloadExcel"
          v-hasPermi="['mes:productionRecord:export']">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <el-table ref="table" height="500" size="mini" v-loading="loading" :data="productionRecordList"
      @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="ID" align="center" prop="id" /> -->
      <el-table-column fixed label="产品条码" align="center" prop="productSn" width="150">
        <template v-slot="scope">
          <router-link :to="'/production/processing/record/' + scope.row.productSn" class="link-type">
            <span>{{ scope.row.productSn }}</span>
          </router-link>
        </template>
      </el-table-column>
      <!-- <el-table-column label="定子码" align="center" prop="定子码" width="180" />
      <el-table-column label="船载码" align="center" prop="船载码" width="180" />
      <el-table-column label="配件码" align="center" prop="配件码" width="180" />
      <el-table-column label="等级评估" align="center" prop="等级评估" width="180" />
      <el-table-column label="第八颗螺丝扭力" align="center" prop="第八颗螺丝扭力" width="180" />
      <el-table-column label="第八颗螺丝角度" align="center" prop="第八颗螺丝角度" width="180" /> -->
      

      <el-table-column label="生产时间" align="center" prop="productionTime" width="180" />
      <el-table-column label="生产工艺" align="center" prop="productionProcessName" width="150">
        <template slot-scope="scope">
          <div @click="getRoutlist(scope.row)" style="color: #337ab7;cursor: pointer;">{{
            scope.row.productionProcessName }}</div>
        </template>
      </el-table-column>
      <el-table-column label="返工工艺" align="center" prop="reworkProcessName" width="150" />
      <!-- <el-table-column label="加工编码" align="center" prop="processCode"/> -->
      <el-table-column label="是否返工" align="center" prop="isRework">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.yes_or_no" :value="scope.row.isRework" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.product_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="返工次数" align="center" prop="reworkCount" />
      <el-table-column label="报废原因" align="center" prop="scrapReason" />
      <!-- <el-table-column label="工艺参数" align="center" prop="processParams"> </el-table-column> -->
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->

      <!--自定义渲染头-->
      <el-table-column align="center" :key="index" v-for="(column, index) in columns " :prop="column.prop"
        :label="column.label">
        <el-table-column align="center" :key="index" v-for="(child, index) in column.children " :prop="child.prop"
          :label="child.label" :width="child.width">
          <template slot-scope="scope">
            <dict-tag v-if="child.dist" :options="dict.type[child.dist]" :value="scope.row[child.prop]" />
            <span v-else v-html="scope.row[child.prop]"></span>
          </template>
        </el-table-column>
      </el-table-column>

      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="80">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleRework(scope.row)">返工
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleScrap(scope.row)">报废
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改生产记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="45%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="180px">

        <el-form-item v-if="flag == 1 && dialogVisible" label="权限密码" prop="processId" style="width: 62%;">
          <el-input v-model="userpassWord" placeholder="请输入权限密码" @input="valuechen" type="password" />
        </el-form-item>

        <el-form-item v-if="flag == 1" label="返工工艺" prop="processId">
          <el-select v-model="form.reworkProcessId" placeholder="请选择" :disabled="dialogVisible">
            <el-option v-for="item in processOptions" :key="item.value" :label="item.label" :value="(item.value)"
              :disabled="item.disabled">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="flag == 2" label="报废原因" prop="scrapReason">
          <el-input v-model="form.scrapReason" type="textarea" placeholder="请输入内容" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="!dialogVisible">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="routeName" :visible.sync="Visiblelook" width="100%">
      <div style="margin: 10 30px;">
        <el-steps :active="steps.length" align-center>
          <el-step v-for="(item, index) in steps" :key="index" :title="item.workstation"
            :description="item.deviceName.substring(0, 6)"></el-step>
        </el-steps>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="Visiblelook = false">取 消</el-button>
        <el-button type="primary" @click="Visiblelook = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {

  listProductionRecordVo,
  getProductionRecord,
  delProductionRecord,

  updateProductionRecord
} from "@/api/mes/production_record";
import { listDeviceParams } from "@/api/mes/device";
import {
  listProcessRoute,
} from "@/api/mes/process_route";
import { listProcess } from '@/api/mes/process';
import SerpentineSteps from "../../../components/SerpentineSteps/index.vue";
import { buildRows, buildColumns } from '@/utils/tableDataList.js';
import { downloadTableData } from "@/utils/excel";
import { getUserProfile } from "@/api/system/user";
import * as XLSX from 'xlsx';
export default {

  name: "ProductionRecord",
  dicts: ['product_status', 'yes_or_no', 'processing_result', 'product_verification_identification', 'sys_password'],
  components: {
    SerpentineSteps,
  },
  data() {
    return {
      dialogVisible: false,
      // 遮罩层
      userpassWord: '',
      Visiblelook: false,
      loading: false,
      // 选中数组
      dateRange: [],
      ids: [],
      // 非单个禁用
      single: true,
      routeName: '',
      currentStep: 5, // 当前步骤索引，从 0 开始
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      processOptions: [],
      // 生产记录表格数据
      productionRecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      flag: null,
      steps: [],
      user: {},
      confirmPasswrod: '',
      // 查询参数
      columnHeaders: {
        productSn: '产品条码',
        processingResult: '加工结果',
        scrapReason: '报废原因',
        productionProcessName: '生产工艺',
        reworkCount: '返工次数',
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        startTime: null,
        // productIdentification: '700W',
        endTime: null,
        productSn: null,
        productionTime: null,
        productionProcessId: null,
        reworkProcessId: null,
        processCode: null,
        isRework: null,
        status: null,
        isSample: null,
        reworkCount: null,
        scrapReason: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      columns: []
    };
  },
  created() {
    const now = new Date();
    const yyyyMMdd = now.toISOString().split('T')[0];
    this.dateRange[0] = yyyyMMdd
    this.dateRange[1] = yyyyMMdd
    this.queryParams.startTime = `${yyyyMMdd} 00:00:00`;
    this.queryParams.endTime = `${yyyyMMdd} 23:59:59`;
    this.getUser();
  },
  mounted() {
    this.getDeviceParams()
    // this.getList();
    this.getProcessList()
    this.getConfigKey("sys.rework.password").then(response => {
      this.confirmPasswrod = response.msg
    });
  },
  methods: {
    getDeviceParams() {
      listDeviceParams().then(response => {
        this.reBuildColumns(response.rows)
      })
    },
    reBuildColumns(rows) {
      let columns = buildColumns(rows)
      this.columns = columns
      this.getList();
    },

    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
      });
    },
    /** 查询生产记录列表 */
    getList() {
      this.loading = true;
      listProductionRecordVo(this.queryParams).then(response => {
        let { rows } = response
        this.reBuildData(rows)
        this.productionRecordList = rows;
        this.total = response.total;
        this.loading = false;
        // rows.forEach(item => {
        //   let productSnPrefix = item.productSn.slice(0, 3);
        //   let productIdentificationPrefix = this.queryParams.productIdentification.slice(0, 3);
        //   if (productSnPrefix == productIdentificationPrefix) {
        //     if (this.queryParams.productIdentification == '700W') {
        //       this.productionRecordList = rows;
        //       this.total = response.total;
        //     }
        //   } else {
        //     console.log(`ID: ${item.id}, productSn: ${item.productSn} 与 productIdentification 前三位不同`);
        //   }

        // });
      });

    },
    reBuildData(list) {
      let rows = buildRows(list)
      this.productionRecordList = rows;
    },
    dictValue() {
      this.queryParams.productIdentification += 'W'
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    parseJson(str) {
      return str ? JSON.parse(str) : [];
    },
    valuechen() {
      if (this.userpassWord == this.confirmPasswrod) {
        this.dialogVisible = false
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productSn: null,
        productionTime: null,
        productionProcessId: null,
        reworkProcessId: null,
        processCode: null,
        isRework: null,
        status: null,
        reworkCount: null,
        scrapReason: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      const now = new Date();
      const yyyyMMdd = now.toISOString().split('T')[0];
      // 重置 dateRange 和 queryParams 的时间范围
      this.dateRange = [yyyyMMdd, yyyyMMdd];
      this.queryParams.startTime = `${yyyyMMdd} 00:00:00`;
      this.queryParams.endTime = `${yyyyMMdd} 23:59:59`;
      this.handleQuery();
    },
    dataCheng() {

      this.queryParams.startTime = this.dateRange[0] + ' 00:00:00'
      this.queryParams.endTime = this.dateRange[1] + ' 23:59:59'

    },
    //工艺
    getProcessList() {
      let queryParams = {
        pageNum: 1,
        pageSize: 100,
        processType: 2
      }
      listProcess(queryParams).then(response => {
        this.processOptions = this.buildOptions(response.rows, { value: 'id', label: 'processName' });
      });
    },
    buildOptions(rows, op) {
      return rows.map(item => {
        return {
          value: item[op.value],
          label: item[op.label]
        }
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加生产记录";
    },
    /** 修改按钮操作 */
    handleRework(row) {
      if (this.user.userId !== 1) {
        this.dialogVisible = true
      }
      this.userpassWord = ''
      this.flag = 1
      this.reset();
      const id = row.id || this.ids
      getProductionRecord(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改返工路径";
      });


    },
    //报废
    handleScrap(row) {
      this.flag = 2
      this.reset();
      const id = row.id || this.ids
      getProductionRecord(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "报废原因";
      });
    },
    /** 提交按钮 */
    submitForm() {

      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.isRework = 1
          this.form.reworkCount = this.form.reworkCount + 1
          this.form.status = 3

          if (this.form.id != null) {
            updateProductionRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除生产记录编号为"' + ids + '"的数据项？').then(function () {
        return delProductionRecord(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    processStyle(text) {
      if (text == null || text === '') {
        return ''
      }
      if (typeof text == 'number') {
        return text
      }
      const tempElement = document.createElement('span');
      tempElement.innerHTML = text.trim();
      if (tempElement.childNodes.length === 1 && tempElement.firstChild.nodeType === 1) {
        return tempElement.firstChild.textContent.trim();
      }
      return text;
    },
    /** 导出按钮操作 */
    downloadExcel() {
      if (true) {
        downloadTableData(this.$refs.table, this.productionRecordList, this.dict.type)
        return
      }
      const data = (this.productionRecordList || []).map(row => {
        console.log(row)
        return Object.keys(row).reduce((obj, key) => {
          if (!obj) {
            return
          }
          let label = this.columnHeaders ? this.columnHeaders[key] : undefined;
          if (label) {
            if (key === 'processingResult') {
              obj[label] = row[key] == 1 ? '合格' : '不合格';
            } else {
              obj[label] = row[key];
            }
          } else {
            if (key.startsWith("OP")) {
              let value = this.processStyle(row[key]);
              obj[key] = value
              if (key.includes('工序结果')) {
                if (value == 1) {
                  obj[key] = 'OK'
                } else if (value == 2) {
                  obj[key] = 'NG'
                }
              }
            }
          }
          return obj;
        }, {});
      });

      if (data.length > 0) {
        const ws = XLSX.utils.json_to_sheet(data);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
        XLSX.writeFile(wb, '加工过程.xlsx');
      } else {
        console.error('No data available to export!');
      }
    },
    containsChinese(str) {
      const regex = /[\u4e00-\u9fa5]+/;
      return regex.test(str);
    },
    getRoutlist(row) {

      let queryParams = {
        pageNum: 1,
        pageSize: 100,
        processId: row.productionProcessId
      }
      listProcessRoute(queryParams).then(response => {
        this.steps = response.rows;

        this.routeName = row.productionProcessName + "路径"
        this.Visiblelook = true
      });
    }
  }
};
</script>


<style>
/* 定义滚动条轨道的样式 */
::-webkit-scrollbar {
  width: 8px;
  /* 滚动条轨道的宽度 */
  height: 12px;
}

.upper {
  color: red;
  font-weight: bold;
  font-size: 16px;
  cursor: pointer;
}

.lower {
  color: blue;
  font-weight: bold;
  font-size: 16px;
  cursor: pointer;
}

.permission {
  display: flex;
  text-align: center;
}
</style>
